package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoaderDataFormat;
	import flash.utils.ByteArray;
	import nochump.util.zip.ZipEntry;
	import nochump.util.zip.ZipFile;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class PptxParser extends Sprite
	{
		private var bytes:ByteArray = null;
		private var zipFile:ZipFile = null;
		private var xml:XML = null;
		private var paragraphs:Array = null;
		
		public function PptxParser(bytes:ByteArray = null)
		{
			super();
			if (bytes)
			{
				this.bytes = bytes;
				unzip();
			}
			else
			{
				SwfLoader.loadData("pptx.pptx", loaded, URLLoaderDataFormat.BINARY);
			}
		}
		
		private function loaded(e:Event):void
		{
			if (e && e.type == Event.COMPLETE)
			{
				bytes = e.target.data as ByteArray;
			}
			unzip();
		}
		
		private function unzip():void
		{
			if (bytes == null)
				return;
			if (zipFile == null)
			{
				zipFile = new ZipFile(bytes);
				trace(zipFile.entries.join("\n"));
				trace("===========================");
			}
			var entry:ZipEntry = zipFile.getEntry("[Content_Types].xml");
			
			if (entry)
			{
				var data:ByteArray = zipFile.getInput(entry);
				if (data)
				{
					xml = XML(data);
					var ns:Namespace = xml.namespace();
					trace("namespace:", ns);
					
					for each (var _entry:ZipEntry in zipFile.entries)
					{
						if (_entry.name.match(/^ppt\/slides\/[^\/]+.xml$/))
						{
							var sheetStream:ByteArray = zipFile.getInput(_entry);
							var str:String = String(sheetStream);
							var sheetXML:XML = XML(str);
							
							if (paragraphs == null)
								paragraphs = new Array();
							
							var filename:String = _entry.name.replace(/^ppt\/slides\/([^\/]+).xml$/, "$1");
							var numRow:int = int(filename.replace(/^[^0-9]*([0-9]+)[^0-9]*$/g, "$1")) - 1;
							paragraphs[numRow] = "\r\n----------- " + filename + " ---------\n";
							/// 	<a:t>text</a:t>
							var arr:Array = str.match(/<a:t>([^<]+)<\/a:t>/g);
							paragraphs[numRow] += arr.join("\n").replace(/<[^<>]+>/g,"");
							trace(paragraphs[numRow]);
							for each (var row:XML in sheetXML.ns::sheetData.children())
							{
								for each (var c:XML in row.children())
								{
									if (c.@t == "s")
									{
										//paragraphs[numRow] += String(ls[int(c.ns::v)]).replace(/[\r\n]/gm, "") + "\t";
									}
								}
							}
						}
					}
				}
			}
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			if (paragraphs)
				addChild(new MyText(3, 10, stage.stageWidth - 6, stage.stageHeight - 10, String(paragraphs.join("\n"))));
			else
				addChild(new MyText(3, 10, stage.stageWidth - 6, stage.stageHeight - 10, String("解析文件出现问题")));
		}
	}
}